package com.ruyuan.eshop.diplomacy.api.impl;

import com.ruyuan.eshop.common.constants.SkuSellerConstant;
import com.ruyuan.eshop.common.constants.diplomacy.AbstractRedisKeyConstants;
import com.ruyuan.eshop.common.core.JsonResult;
import com.ruyuan.eshop.common.exception.ProductErrorCodeEnum;
import com.ruyuan.eshop.common.utils.ParamCheckUtil;
import com.ruyuan.eshop.diplomacy.api.ProductSaleApi;
import com.ruyuan.eshop.diplomacy.converter.SkuSellerConverter;
import com.ruyuan.eshop.diplomacy.domain.dto.ProductSaleCollectDTO;
import com.ruyuan.eshop.diplomacy.domain.dto.ProductSaleRelationDTO;
import com.ruyuan.eshop.diplomacy.domain.dto.SaleContentDTO;
import com.ruyuan.eshop.diplomacy.domain.entity.SkuSellerRelationDO;
import com.ruyuan.eshop.diplomacy.domain.query.ProductSaleQuery;
import com.ruyuan.eshop.diplomacy.domain.query.ProductSaleRelationQuery;
import com.ruyuan.eshop.diplomacy.manager.custom.cache.SkuSellerCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.ruyuan.eshop.common.constants.diplomacy.BaseConstants.PAGE_NO_1;
import static com.ruyuan.eshop.common.constants.diplomacy.BaseConstants.PAGE_SIZE_1000;

/**
 * 商品售卖服务
 *
 * @author zhonghuashishan
 */
@Slf4j
@DubboService(version = "1.0.0", interfaceClass = ProductSaleApi.class, retries = 0)
public class ProductSaleApiImpl implements ProductSaleApi {

    @Resource
    private SkuSellerCache skuSellerCache;

    @Resource
    private SkuSellerConverter skuSellerConverter;

    /**
     * 分页查询卖家类型下的可售商品
     *
     * @param productSaleQuery
     * @return com.ruyuan.eshop.common.core.JsonResult<com.ruyuan.eshop.diplomacy.domain.dto.ProductSaleDTO>
     * @author zhonghuashishan
     */
    @Override
    public JsonResult<ProductSaleCollectDTO> getSaleSku(ProductSaleQuery productSaleQuery) {
        ParamCheckUtil.checkObjectNonNull(productSaleQuery);
        ParamCheckUtil.checkIntegerNonEmpty(productSaleQuery.getSellerType());
        ParamCheckUtil.checkIntegerNonEmpty(productSaleQuery.getPageNo());
        ParamCheckUtil.checkIntegerNonEmpty(productSaleQuery.getPageSize());

        int pageNo = PAGE_NO_1;
        int pageSize = PAGE_SIZE_1000;
        if(Objects.nonNull(productSaleQuery.getPageNo())) {
            pageNo = productSaleQuery.getPageNo();
        }
        if(Objects.nonNull(productSaleQuery.getPageSize())) {
            pageSize = productSaleQuery.getPageSize();
        }
        int offset = (pageNo - 1) * pageSize;
        String redisKey = AbstractRedisKeyConstants.getSellerSaleSkuZsetKey(productSaleQuery.getSellerType());
        Optional<List<String>> optional = skuSellerCache.listRedisSortedSetData(redisKey, offset, pageSize);
        if(!optional.isPresent()) {
            return JsonResult.buildError(ProductErrorCodeEnum.NO_RESULT_ERROR.getErrorCode(), ProductErrorCodeEnum.NO_RESULT_ERROR.getErrorMsg());
        }

        boolean nextPage = false;
        Long count = skuSellerCache.zcard(redisKey);
        if(count.intValue() > (offset + pageSize)) {
            nextPage = true;
        }

        ProductSaleCollectDTO productSaleCollectDTO = new ProductSaleCollectDTO();
        productSaleCollectDTO.setSkuIdList(optional.get());
        productSaleCollectDTO.setNextPage(nextPage);
        productSaleCollectDTO.setTotal(count);
        return JsonResult.buildSuccess(productSaleCollectDTO);
    }

    /**
     * 根据卖家ID和商品编码判断商品是否可售
     *
     * @param productSaleRelationQuery
     * @return com.ruyuan.eshop.common.core.JsonResult<com.ruyuan.eshop.diplomacy.domain.dto.ProductSaleRelationDTO>
     * @author zhonghuashishan
     */
    @Override
    public JsonResult<ProductSaleRelationDTO> getProductSaleRelationSku(ProductSaleRelationQuery productSaleRelationQuery) {

        ParamCheckUtil.checkObjectNonNull(productSaleRelationQuery);
        ParamCheckUtil.checkCollectionNonEmpty(productSaleRelationQuery.getProductIdList());
        ParamCheckUtil.checkCollectionNonEmpty(productSaleRelationQuery.getSellerIdList());

        // 先获取得到卖家的可售商品列表
        Optional<List<SkuSellerRelationDO>> optional = skuSellerCache.listRedisStringData(productSaleRelationQuery.getSellerIdList());

        List<SkuSellerRelationDO> sellerRelationDOList = new ArrayList<>();
        if (optional.isPresent()){
            sellerRelationDOList = optional.get();
        }
        // 构建可售商品和卖家关系,以及不可售商品列表
        ProductSaleRelationDTO productSaleRelationDTO = buildProductSaleRelation(sellerRelationDOList,productSaleRelationQuery.getProductIdList());
        return JsonResult.buildSuccess(productSaleRelationDTO);
    }

    /**
     * 处理商品是否在可售范围内
     * @param sellerRelationDOList
     * @param productIdList
     * @return
     */
    private ProductSaleRelationDTO buildProductSaleRelation(List<SkuSellerRelationDO> sellerRelationDOList, Set<String> productIdList) {
        // 售卖关系对象
        List<SaleContentDTO> saleContentDTOList = new ArrayList<>();
        List<String> notSaleProductId = new ArrayList<>();
        // 将集合转换为map
        Map<String, SkuSellerRelationDO> skuSellerRelationDOMap = sellerRelationDOList.stream().collect(Collectors.toMap(SkuSellerRelationDO::getSkuId, Function.identity()));
        // 开始遍历哪些商品可售了
        for (String productId:productIdList){
            if (skuSellerRelationDOMap.containsKey(productId)){
                SkuSellerRelationDO skuSellerRelationDO = skuSellerRelationDOMap.get(productId);
                if (skuSellerRelationDO.getRelationType().equals(SkuSellerConstant.RELATION_TYPE_01)){
                    saleContentDTOList.add(skuSellerConverter.converterDTO(skuSellerRelationDO));
                    continue;
                }
            }
            notSaleProductId.add(productId);
        }
        Map<Long, List<SaleContentDTO>> saleContentMap = saleContentDTOList.stream().collect(Collectors.groupingBy(SaleContentDTO::getSellerId));
        return new ProductSaleRelationDTO(saleContentMap,notSaleProductId);
    }


}
